package com.ruoyi.security.service.backtest.gridtrading.processor.impl;

import com.ruoyi.security.service.backtest.gridtrading.context.BacktestContext;
import com.ruoyi.security.service.backtest.gridtrading.processor.AbstractTradeProcessor;
import org.springframework.stereotype.Component;

/**
 * @author yeoman
 * @date 2025/11/8 00:01
 * @description
 */
@Component("sellTradeProcessor")
public class SellTradeProcessor extends AbstractTradeProcessor {
    @Override
    protected void updateContext(BacktestContext context) {
        BacktestContext.BacktestVariable backtestVariable = context.getBacktestVariable();
        BacktestContext.BacktestVariable.TradeInfo tradeInfo = backtestVariable.getTradeInfo();
        BacktestContext.BacktestVariable.DayTradeInfo.Sell dayTradeInfoSell = backtestVariable.getDayTradeInfo().getSell();
        BacktestContext.BacktestVariable.TotalTradeInfo.Sell totalTradeInfoSell = backtestVariable.getTotalTradeInfo().getSell();

        // 更新当前持仓
        backtestVariable.setPosition(backtestVariable.getPosition() - tradeInfo.getTradeQuantity());
        // 更新可用资金
        if (backtestVariable.getAvailableAmount() != null) {
            backtestVariable.setAvailableAmount(backtestVariable.getAvailableAmount().add(tradeInfo.getTradeAmount()));
        }

        /*更新当日信息*/
        // 更新当日卖出次数
        dayTradeInfoSell.setDaySellCount(dayTradeInfoSell.getDaySellCount() + 1);
        // 更新当日卖出数量
        dayTradeInfoSell.setDaySellQuantity(dayTradeInfoSell.getDaySellQuantity() + tradeInfo.getTradeQuantity());
        // 更新当日卖出金额
        dayTradeInfoSell.setDaySellAmount(dayTradeInfoSell.getDaySellAmount().add(tradeInfo.getTradeAmount()));
        // 更新当日卖出手续费
        dayTradeInfoSell.setDaySellChargeAmount(dayTradeInfoSell.getDaySellChargeAmount().add(tradeInfo.getTradeChargeAmount()));

        /*更新总信息*/
        // 更新总的卖出次数
        totalTradeInfoSell.setTotalSellCount(totalTradeInfoSell.getTotalSellCount() + 1);
        // 更新总的卖出数量
        totalTradeInfoSell.setTotalSellQuantity(totalTradeInfoSell.getTotalSellQuantity() + tradeInfo.getTradeQuantity());
        // 更新总的卖出金额
        totalTradeInfoSell.setTotalSellAmount(totalTradeInfoSell.getTotalSellAmount().add(tradeInfo.getTradeAmount()));
        // 更新总的卖出手续费
        totalTradeInfoSell.setTotalSellChargeAmount(totalTradeInfoSell.getTotalSellChargeAmount().add(tradeInfo.getTradeChargeAmount()));

        // 更新当前投入资金
        backtestVariable.setInvestmentAmount(backtestVariable.getInvestmentAmount().subtract(tradeInfo.getTradeAmount()));
    }
}
